package seatiger.tomcat.catalina.core;

import seatiger.tomcat.catalina.*;
import seatiger.tomcat.catalina.connector.NewRequest;
import seatiger.tomcat.catalina.connector.NewResponse;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * context 管道中的基础阀
 */
public class StandardContextValve extends ValveBase {
    @Override
    public String getInfo() {
        return "seatiger.tomcat.catalina.core.StandardContextValve/1.0";
    }

    @Override
    @Deprecated
    public void invoke(Request request, Response response, ValveContext context) throws IOException, ServletException {
        Container container = getContainer();
        Container wrapper = container.map(request, true);
        String requestURI = ((HttpRequest) request).getDecodedRequestURI();
        if (wrapper == null) {
            notFound(requestURI, (HttpServletResponse) response.getResponse());
            return;
        }
        wrapper.invoke(request, response);
    }

    private void notFound(String requestURI, HttpServletResponse response) {
        try {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, requestURI);
        } catch (IllegalStateException | IOException e) {
        }
    }

    @Override
    public void invoke(NewRequest request, NewResponse response) throws IOException, ServletException {
        Wrapper wrapper = request.getWrapper();
        wrapper.getPipeline().getFirst().invoke(request,response);
    }
}
